package com.ruoyi.web.controller.thesis;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.thesis.domain.SysFileInfo;
import com.ruoyi.thesis.domain.ThesisMapping;
import com.ruoyi.thesis.service.ISysFileInfoService;
import com.ruoyi.thesis.service.IThesisMappingService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件信息Controller
 *
 * @author yangquanxin
 * @date 2020-09-13
 */
@Controller
@RequestMapping("/thesis/checkreport")
public class CheckReportController extends BaseController {
    private String prefix = "thesis/checkreport";



    @Autowired
    private IThesisMappingService thesisMappingService;

    @RequiresPermissions("thesis:checkreport:view")
    @GetMapping()
    public String info()
    {
        return prefix + "/checkreport";
    }

    /**
     * 查询文件信息列表
     */
    @RequiresPermissions("thesis:checkreport:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ThesisMapping thesisMapping)
    {
        startPage();
        // 学生自建题目需要限制学生只看到自己的题目，教师能看到自己论文的
        SysUser currentUser = ShiroUtils.getSysUser();
        String roleKeys = currentUser.getRoleKeys();
        if (roleKeys.contains("teacher")){
            Map<String,Object> map = new HashMap<>();
            map.put("dsf"," and t.teacher_id = '"+ShiroUtils.getUserId()+"' ");
            thesisMapping.setParams(map);
        }else if (roleKeys.contains("student")){
            Map<String,Object> map = new HashMap<>();
            map.put("dsf"," and t.student_id = '"+ShiroUtils.getUserId()+"' ");
            thesisMapping.setParams(map);
        }
        List<ThesisMapping> list = thesisMappingService.selectThesisMappingList(thesisMapping);
        return getDataTable(list);

    }
    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        // 本地资源路径
        String localPath = Global.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
//        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//        FileUtils.setAttachmentResponseHeader(response, downloadName);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
    /**
     * 导出文件信息列表
     */
    @RequiresPermissions("thesis:checkreport:export")
    @Log(title = "检测报告", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ThesisMapping thesisMapping)
    {
        List<ThesisMapping> list = thesisMappingService.selectThesisMappingList(thesisMapping);
        ExcelUtil<ThesisMapping> util = new ExcelUtil<ThesisMapping>(ThesisMapping.class);
        return util.exportExcel(list, "mapping");
    }

    /**
     * 新增文件信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存文件信息
     */
    @RequiresPermissions("thesis:checkreport:add")
    @Log(title = "检测报告", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, ThesisMapping thesisMapping) throws IOException
    {
        // 上传文件路径
        String filePath = Global.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        thesisMapping.setCheckreport_url(fileName);
        return toAjax(thesisMappingService.updateThesisMapping(thesisMapping));
    }


    /**
     * 修改文件信息
     */
    @GetMapping("/edit/{tmId}")
    public String edit(@PathVariable("tmId") Long tmId, ModelMap mmap)
    {
        ThesisMapping thesisMapping = thesisMappingService.selectThesisMappingById(tmId);
        mmap.put("thesisMapping", thesisMapping);
        return prefix + "/edit";
    }

    /**
     * 修改保存文件信息
     */
    @RequiresPermissions("thesis:checkreport:edit")
    @Log(title = "检测报告", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam("file") MultipartFile file, ThesisMapping thesisMapping) throws IOException {

        // 上传文件路径
        String filePath = Global.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        thesisMapping.setCheckreport_url(fileName);
        return toAjax(thesisMappingService.updateThesisMapping(thesisMapping));
    }

    /**
     * 删除文件信息
     */
    @RequiresPermissions("thesis:checkreport:remove")
    @Log(title = "文件信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(thesisMappingService.deleteThesisMappingById(Long.getLong(ids)));
    }
}
